use loco_rs::prelude::*;
use sea_orm::DeleteResult;
use serde::{Deserialize, Serialize};

pub use super::_entities::model_has_roles::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub role_id: String,
    pub model_type: String,
    pub model_id: String,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Role ID must not be empty."))]
    pub role_id: String,
    #[validate(length(min = 1, message = "Model Type must not be empty."))]
    pub model_type: String,
    #[validate(length(min = 1, message = "Model ID must not be empty."))]
    pub model_id: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            role_id: self.role_id.as_ref().to_owned(),
            model_type: self.model_type.as_ref().to_owned(),
            model_id: self.model_id.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::model_has_roles::ActiveModel {
    async fn before_save<C>(self, _db: &C, _insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        Ok(self)
    }
}

impl Model {
    /// finds model roles by the provided role id
    ///
    /// # Errors
    ///
    /// When could not find model roles or DB query error
    pub async fn find_by_role_id(db: &DatabaseConnection, role_id: &str) -> ModelResult<Vec<Self>> {
        let model_roles = model_has_roles::Entity::find()
            .filter(
                model::query::condition()
                    .eq(model_has_roles::Column::RoleId, role_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(model_roles)
    }

    /// finds model roles by the provided model type and model id
    ///
    /// # Errors
    ///
    /// When could not find model roles or DB query error
    pub async fn find_by_model(
        db: &DatabaseConnection,
        model_type: &str,
        model_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let model_roles = model_has_roles::Entity::find()
            .filter(
                model::query::condition()
                    .eq(model_has_roles::Column::ModelType, model_type)
                    .eq(model_has_roles::Column::ModelId, model_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(model_roles)
    }

    /// Asynchronously creates a model role and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the model role into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let model_role = model_has_roles::ActiveModel {
            role_id: ActiveValue::set(params.role_id.to_string()),
            model_type: ActiveValue::set(params.model_type.to_string()),
            model_id: ActiveValue::set(params.model_id.to_string()),
        }
        .insert(db)
        .await?;

        Ok(model_role)
    }

    /// Deletes the model role
    ///
    /// # Errors
    ///
    /// When could not delete the model role from the DB
    pub async fn delete(self, db: &DatabaseConnection) -> ModelResult<DeleteResult> {
        let model: model_has_roles::ActiveModel = self.into();
        Ok(model.delete(db).await?)
    }
}
